package gov.pbc.nn.kjgl.train.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.kjgl.entity.TrainingDept;
import gov.pbc.nn.kjgl.entity.TrainingPlan;
import gov.pbc.nn.kjgl.entity.TrainingUser;

@Repository
public class TrainRegisterDao extends AbstractHibernateDao {
	
	@Autowired
	private TrainPlanDao trainPlanDao;
	
	
	public TrainingPlan selectTrainPlanById(String id) {
		DetachedCriteria query = DetachedCriteria.forClass(TrainingPlan.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		query.add(Restrictions.eq("id", id));
		List<TrainingPlan> ls = (List<TrainingPlan>) this.query(query);
		if (ls.size() > 0) {
			return ls.get(0);
		}
		return null;
	}

	public void insertMeetingUser(TrainingPlan trainPlan, Map<String, Object> parameter) {
		int i = checkMeetingUser((String) parameter.get("username"), trainPlan.getId());
		if (i < 1) {
			TrainingUser tu = new TrainingUser();
			tu.setUsername((String) parameter.get("username"));
			tu.setCname((String) parameter.get("cname"));
			tu.setEname((String) parameter.get("ename"));
			tu.setDeptId((String) parameter.get("deptId"));
			tu.setDeptName((String) parameter.get("deptName"));
			tu.setBusKey(trainPlan.getId());
			this.save(tu);
			
			int count=trainPlanDao.getCountUser(trainPlan.getId());
			trainPlan.setPeoples(count);
			this.update(trainPlan);
		}
	}
	/**
	 * 判断人员添加是否重复
	 * @param username
	 * @param busKey
	 * @return
	 */

	public int checkMeetingUser(String username, String busKey) {
		String hql = "select count(*) from TrainingUser where busKey=:busKey and username=:username and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("busKey", busKey);
		map.put("username", username);
		return this.queryForInt(hql, map);
	}

	/**
	 *判断 当前时间是否比结束时间小
	 * @param id	
	 * @return
	 */
	public boolean getTime(String id) {
		String hql = "from TrainingDept where invalid=false and busKey=:id";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<TrainingDept> lsDepts = this.query(hql, map);
		if(lsDepts.size()>0){
			Date endTime = lsDepts.get(0).getEndTime();
			Date newDate = new Date();
			if (newDate.getTime() < endTime.getTime()) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

}
